package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.domain.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //创建employee对象将接收到的数据复制到employee对象中
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置初始状态为启用
        employee.setStatus(StatusConstant.ENABLE);
        //设置初始密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间和更新时间(因为使用了AutoFillAspect切面方法,不必手动设置)
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //记录创建人的id和修改人的id(因为使用了AutoFillAspect切面方法,不必手动设置)
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //保存到数据库中
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageDto
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageDto) {
        //使用分页工具提取分页参数
        PageHelper.startPage(employeePageDto.getPage(), employeePageDto.getPageSize());
        //使用mapper进行分页查询,获取泛型为Employee的分页对象
        Page<Employee> page = employeeMapper.page(employeePageDto);
        //总记录数
        long total = page.getTotal();
        //当前页数据集合
        List<Employee> result = page.getResult();
        //将数据封装到PageResult对象并返回
        return new PageResult(total, result);
    }

    /**
     * 员工状态修改
     *
     * @param status
     * @param id
     */
    @Override
    public void setStatus(Integer status, Long id) {
        //本质就是更新员工状态
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                //设置更新时间和更新操作人(因为使用了AutoFillAspect切面方法,不必手动设置)
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据ID查询员工
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //隐藏密码,不能将真实密码暴露给前端
        employee.setPassword("****");
        return employee;
    }

    /**
     * 根据ID修改员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //创建员工实体对象
        Employee employee = new Employee();
        //将接收到的DTO的数据复制到实体对象中
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置更新时间和更新操作人(因为使用了AutoFillAspect切面方法,不必手动设置)
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //更新数据库
        employeeMapper.update(employee);
    }

}
